package com.flyxiaozhu.erp.core.libs;

import com.flyxiaozhu.erp.core.entities.GoodsOrder;
import com.flyxiaozhu.erp.core.entities.GoodsSku;
import com.flyxiaozhu.erp.core.entities.Goods;
import com.flyxiaozhu.erp.core.entities.GoodsOrderDetail;
import com.flyxiaozhu.erp.core.repositories.GoodsRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsSkuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 库存管理
 * 主要用于对库存的锁定和解锁，并不是使用琐机制，而是实际执行update语句，去消化和增加库存
 */
@Component
public class StockManager {
    @Autowired
    GoodsRepository goodsRepository;

    @Autowired
    GoodsSkuRepository goodsSkuRepository;

    //消耗一个库存
    public JSONResult lockStock(Goods goods, GoodsOrderDetail detail, GoodsSku nullableSku, GoodsOrder order) throws AppException {
        if (goods.getStock() <= 0) {
            return new JSONResult(ErrorCode.LOW_STOCKS, "库存不足");
        }

        if (nullableSku != null) {
            if (nullableSku.getStock() <= 0) {
                return new JSONResult(ErrorCode.LOW_STOCKS, "库存不足");
            }
            goodsSkuRepository.decStock(nullableSku.getId(), detail.getGoodsNum());
        }

        goodsRepository.decStock(goods.getId(), detail.getGoodsNum());

        detail.setDeliveryStatus(Constants.DELIVERY_STATUS_LOCKED);

        return new JSONResult();
    }

    //退回库存
    public void refundStock(Goods goods, GoodsOrderDetail detail, GoodsSku nullableSku, GoodsOrder order) {
        goodsRepository.incStock(goods.getId(), detail.getGoodsNum());
        if (nullableSku != null) {
            goodsSkuRepository.incStock(nullableSku.getId(), detail.getGoodsNum());
        }
        detail.setDeliveryStatus(Constants.DELIVERY_STATUS_UNLOCK);
    }
}
